//
//  MJRefreshController.swift
//  新浪微博
//
//  Created by MaJi on 16/4/15.
//  Copyright © 2016年 MaJi. All rights reserved.
//

import UIKit
import SnapKit
class MJRefreshController: UIControl {
    let refreshHight:CGFloat = 60
//swift 中的枚举
    enum MJRefreshStatue:Int {
        case Normal = 0//普通状态
        case Pulling = 1//准备刷新状态
        case Refreshing = 2//正在刷新状态
    }
     var statue:MJRefreshStatue = .Normal {
        didSet{
            switch statue {
            case .Normal:
                tipLabel.text = "下拉起飞"
                //停止转动小菊花
                indictorView.stopAnimating()
//                显示剪头
                arrowicon.hidden = false
//                将剪头显示为默认状态
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowicon.transform = CGAffineTransformIdentity//回到旋转原来的位置
                    }, completion: nil)
//                如果之前的值是正在刷新状态,修改他的contentOffset.top
                if oldValue == .Refreshing {
                    var insetTop = self.scrollView!.contentInset.top
                    insetTop = insetTop - self.refreshHight
                    self.scrollView?.contentInset.top = insetTop
                }
            case .Pulling:
                tipLabel.text = "马上起飞"
//                旋转剪头
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowicon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                    
                })
            case .Refreshing:
                tipLabel.text = "正在刷新ing"
//                隐藏箭头
                arrowicon.hidden = true
//                开启菊花转
                indictorView.startAnimating()
                //刷新数据 等待数据刷新成功之后  将状态改为 普通状态
                //主动给当前控件发送对应的事件类型 会自动找到对应的target 调用监听的方法
//                注意只有实行了此方法,才能实现方法,进行刷新数据
//                停留0.25秒 设置contentOffset.top 让菊花转停留
                sendActionsForControlEvents(.ValueChanged)
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    var insetTop = self.scrollView!.contentInset.top
                    insetTop = insetTop + self.refreshHight
                    self.scrollView?.contentInset.top = insetTop
                    }, completion: nil)
            }
        }
    }
//    结束刷新,延迟恢复.Normal
    func endRefreshing(){
        let delta = dispatch_time(DISPATCH_TIME_NOW,Int64(Double(NSEC_PER_SEC) * 0.8))
        dispatch_after(delta, dispatch_get_main_queue()) { () -> Void in
            self.statue = .Normal
        }
    }
    
    override init(var frame: CGRect) {
//        设置rect,不然在控制器中看不到
        frame = CGRect(x: 0, y: -refreshHight, width: screenWidth, height: refreshHight)
        super.init(frame: frame)
        setupUI()
//        self.backgroundColor = UIColor.redColor()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//    实现KVO的方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        注意一下值都是负数
        let contentOffSetY = scrollView?.contentOffset.y
//        print(contentOffSetY)//
        let targetOffsetY = -scrollView!.contentInset.top - refreshHight
        if scrollView!.dragging {
            if contentOffSetY > targetOffsetY{
//                
//                print("普通")
                statue = .Normal
            }else{
//                print("准备起飞")
                statue = .Pulling
            }
        }else{
//            //没有拽动tableView && 当前状态是 准备刷新状态 才修改为 正在刷新状态
            if statue == .Pulling {
//                print("正在刷新")
                statue = .Refreshing
                //转动小菊花
//                indictorView.startAnimating()
                //隐藏箭头
                arrowicon.hidden = true
            }
        }
    }
//    将要添加到父视图的时候会调用
    override func willMoveToSuperview(newSuperview: UIView?) {
        if let myFather = newSuperview as? UIScrollView{
            
            //        记录父视图
            self.scrollView = myFather
            //当前的刷新控件支持在滚动视图上添加
            //实时的获取滚动视图垂直方向的位移
            /*
            Observer: 要添加的观察着
            forKeyPath: 要观察的键值属性
            options:
            
            //作用:观察对象的属性变化
            */
            
            //        KVO,监听父视图的属性contentOffset的变化 
//            注意一定要实现方法,和移除观察者,否则会蹦
            myFather.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        }
    }
    
    deinit{
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    func setupUI(){
        backgroundColor = UIColor.yellowColor()
        addSubview(arrowicon)
        addSubview(tipLabel)
        addSubview(indictorView)
        indictorView.hidden = false
        
//        布局子控件
       arrowicon.snp_makeConstraints { (make) -> Void in
        make.centerY.equalTo(self.snp_centerY)
        make.centerX.equalTo(self.snp_centerX).offset(-30)
        }
        tipLabel.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self.snp_centerY)
            make.left.equalTo(arrowicon.snp_right)
        }
        indictorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowicon.snp_center)
        }
    }
//    懒加载子视图
    private var scrollView:UIScrollView?
    private lazy var arrowicon = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    private lazy var tipLabel = UILabel(text: "下拉刷新", textColor: UIColor.darkGrayColor(), fontSize: 12)
    private lazy var indictorView:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
}
